package com.zhilianbao.leyaogo.http.interceptor;

import android.os.Build;

import com.bql.convenientlog.CLog;
import com.zhilianbao.leyaogo.BuildConfig;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 自定义Log拦截器 打印信息 <br>
 * Created by Cyarie on 2016/3/24.
 */
public class LogInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long t1 = System.nanoTime();
        Request userAgentRequest = request.newBuilder().addHeader("UserManageFragment-Agent", getUserAgent()).build();
        if (null != userAgentRequest.body())
            CLog.i(String.format("Sending request (%s)  %s on %s%ncontentType:%s%n%s",
                    userAgentRequest.method(), userAgentRequest.url(), chain.connection(), userAgentRequest.body().contentType(), userAgentRequest.headers()));
        Response response = chain.proceed(request);
        long t2 = System.nanoTime();
        CLog.i(String.format("Received response for %s in %.1fms%nHttp status code:%s%ncontentType:%s%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.code(), response.body().contentType(), response.headers()));
        return response;
    }

    /**
     * 解析请求体  如果打印信息的时候 使用该方法  上传文件的时候  进度回调会执行两次即第一次很快完成  又重新开始一次
     *
     * @param request
     * @return
     */
    //    private String parseRequestBody(final Request request) {
    //        try {
    //            final Request copy = request.newBuilder().build();
    //            final Buffer buffer = new Buffer();
    //            copy.body().writeTo(buffer);
    //            return buffer.readUtf8();
    //        } catch (final IOException e) {
    //            return "something error when show requestBody";
    //        }
    //    }

    /**
     * 获取硬件信息
     *
     * @return
     */
    public String getUserAgent() {
        StringBuilder sb = new StringBuilder();
        sb.append(" OS:Android " + Build.VERSION.RELEASE);//Android操作系统版本
        sb.append(" model:" + Build.MODEL);//手机型号
        sb.append(" brand:" + Build.BRAND);//手机品牌
        sb.append(" SDK:" + Build.VERSION.SDK_INT);//SDK版本
        sb.append(" applicationID:" + BuildConfig.APPLICATION_ID);//应用包名
        sb.append(" versionName:" + BuildConfig.VERSION_NAME);//版本名称
        sb.append(" versionCode:" + BuildConfig.VERSION_CODE);//版本号
        return sb.toString();
    }
}
